<template>
  <div>
    <el-dialog
      title=""
      :visible.sync="upload.open"
      width="420px"
      append-to-body
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-upload
        class="upload-demo"
        ref="upload"
        drag
        action="#"
        :auto-upload="false"
        :file-list="upload.fileInfo"
        :limit="1"
        accept=".xlsx"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        style="margin: 5px 0 0 30px"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <div slot="tip">
          <el-tooltip
            content="请严格按照excel模板格式上传数据"
            effect="dark"
            placement="bottom"
          >
            <i class="el-icon-warning"></i>
          </el-tooltip>
          <span>仅允许导入xlsx格式文件</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="downloadTemplate"
            >(下载模板)</el-link
          >
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">上 传</el-button>
        <el-button @click="uploadCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import XLSX from "xlsx";
export default {
  props: {
    moban: String,
    relations: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      upload: {
        open: false,
        fileInfo: [],
      },
    };
  },
  methods: {
    //打开对话框
    dialogOpen() {
      this.upload.open = true;
    },
    //模板下载
    downloadTemplate() {
      let a = document.createElement("a");
      if (this.moban == "deviceBind") {
        a.href = `../.././static/deviceBind.xlsx`;
        a.download = "设备绑定导入模板.xlsx";
      } else if (this.moban == "paramsMaintenance") {
        a.href = `../.././static/paramsMaintenance.xlsx`;
        a.download = "参数维护导入模板.xlsx";
      } else if (this.moban == "projectMaintenance") {
        a.href = `../.././static/projectMaintenance.xlsx`;
        a.download = "项目维护导入模板.xlsx";
      } else if (this.moban == "projectMaintenance_detail") {
        a.href = `../.././static/projectMaintenance_detail.xlsx`;
        a.download = "项目维护-维护详情导入模板.xlsx";
      } else if (this.moban == "approveEmail") {
        a.href = `../.././static/approveEmail.xlsx`;
        a.download = "审批管理导入模板.xlsx";
      }
      a.click();
    },
    //文件个数限制
    handleExceed(file, fileList) {
      if (fileList.length >= 1) {
        this.$modal.msgError("最多上传1个文件，请移除文件后重新选择！");
      }
    },
    //移除文件
    handleRemove(file, fileList) {
      this.upload.fileInfo = fileList;
    },
    //上传
    async submitFileForm() {
      let uploadFiles = this.$refs.upload.uploadFiles;
      if (uploadFiles.length == 0) {
        this.$modal.msgError("请选择文件");
      } else {
        let fileItem = uploadFiles[0].raw;
        let data = await this.readFile(fileItem);
        // 解析文件为二进制数据，将二级制数据变成excel表格式的数据
        let workbook = XLSX.read(data, { type: "binary" });
        //取第一个sheet表的数据转换成JSON格式
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        data = XLSX.utils.sheet_to_json(worksheet);
        let isMoban = false;
        // console.log(this.relations, data, "this.relations");
        //判断Object.keys(item)是否与this.relations相等
        if (
          Object.keys(data[0]).toString() ==
          Object.keys(this.relations).toString()
        ) {
          isMoban = true;
        }
        if (isMoban) {
          //数据处理:键值由中文转英文
          var reqArr = data.map((item) => {
            var newInfo = {};
            //Object.keys(item):['设备名称', '设备编号','使用课别']
            Object.keys(item).forEach((key) => {
              newInfo[this.relations[key]] = item[key];
            });
            return newInfo;
          });
          // console.log(reqArr, "处理后");
          //调用父方法
          this.$emit("child-event", reqArr, fileItem);
        } else {
          this.$modal.msgError("请使用正确的模板文件");
        }
      }
    },
    //取消
    uploadCancel() {
      this.upload.open = false;
      this.upload.fileInfo = [];
    },
    // 按照二进制读取文件
    readFile(file) {
      return new Promise((resolve) => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = (e) => {
          resolve(e.target.result);
        };
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0px 0px;
}
</style>